package cdc.cs.config;

import cdc.cs.common.JSONResult;
import org.apache.http.client.ClientProtocolException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;

/**
 * @ClassName: CustomExceptionHandler
 * @Description: 自定义异常处理
 * @Author: kevin
 * @Date: 2020/4/30 14:48
 * @Version: 1.0
 */
@RestControllerAdvice
public class CustomExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult handlerInterfaceParam(MethodArgumentNotValidException e) {
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return JSONResult.errorException(objectError.toString());
    }

    @ExceptionHandler(NullPointerException.class)
    public JSONResult handlerInterfaceNullException(NullPointerException e) {
        return JSONResult.errorException("这是一个NullPointerException异常: " + e.getMessage());
    }

    @ExceptionHandler(ArithmeticException.class)
    public JSONResult handlerInterfaceRun(ArithmeticException e) {
        return JSONResult.errorException("这是一个ArithmeticException异常: " + e.getMessage());
    }

    @ExceptionHandler(IOException.class)
    public JSONResult handlerIOException(IOException e) {
        return JSONResult.errorException("网络请求异常: " + e.getMessage());
    }

    @ExceptionHandler(ClientProtocolException.class)
    public JSONResult handlerClientProtocolException(ClientProtocolException e) {
        return JSONResult.errorException("网络客户端请求异常: " + e.getMessage());
    }
}
